package co.uk.j_wp.games.topdowngame.level;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;


import co.uk.j_wp.games.topdowngame.Game;
import co.uk.j_wp.games.topdowngame.tile.Tile;
import co.uk.j_wp.games.topdowngame.tile.TileMap;

public class LevelLoader {
	private TileMap tileMap;
	private Tile[] tiles;
	private int width;
	private int height;
	private int startPosX = 0;
	private int startPosY = 0;
	private boolean d = false;

	public LevelLoader(String string, TileMap tileMap) throws IOException {

		this.tileMap = tileMap;

		InputStream is = getClass().getResourceAsStream(string);
		BufferedImage image = ImageIO.read(is);

		int iwidth = image.getWidth();
		int iheight = image.getHeight();
		int maxy = 0;
		int maxx = 0;
		for (int y = 0; y < iheight; y++) {
			for (int x = 0; x < iwidth; x++) {
				if ((image.getRGB(x, y) >> 24 & 0xff) != 0) {
					maxy = max(y, maxy);
					maxx = max(x, maxx);
					if(d)System.out.print(".");
				}else{
					if(d)System.out.print("#");
				}
			}
			if(d)System.out.println();
		}

		if(d)System.out.println("level size = " + maxx + "," + maxy);

		this.width = maxx+1;
		this.height = maxy+1;
		this.tiles = new Tile[height * width];
		for (int xy = 0; xy < width * height; xy++) {
			int x = xy % width;
			int y = xy / width;
			tiles[xy] = getTileForPixel(image.getRGB(x, y), x, y);
		}
	}

	private Tile getTileForPixel(int color, int x, int y) {
		switch (color & 0xffffff) {
		case 0xad966a:
			startPosX = x * Game.TILE_SIZE + Game.TILE_SIZE / 2;
			startPosY = y * Game.TILE_SIZE + Game.TILE_SIZE / 2;
			return floorTile();
		case 0x000000:
			return wallTile();
		case 0xffffff:
			return floorTile();
		default:
			return null;
		}
	}

	private Tile floorTile() {
		Tile t = new Tile(tileMap.getTileColors(2, 0));
		t.setPassable(true);
		return t;
	}

	private Tile wallTile() {
		Tile t = new Tile(tileMap.getTileColors(0, 0));
		t.setPassable(false);
		return t;
	}

	private int max(int y, int maxy) {
		return y > maxy ? y : maxy;
	}

	public static void main(String[] args) throws IOException {
		Level l = new Level(null, new LevelLoader("/map.png", new TileMap("/tex.png"))).debug();
		System.out.println("size: " + l.getTilesXCount() + "," + l.getTilesYCount());
	}

	private void debug() {

	}

	public int getWidth() {
		return width;
	}

	public int getHeight() {
		return height;
	}

	public Tile[] getTiles() {
		return tiles;
	}

	public int getStartPosX() {
		return startPosX;
	}

	public int getStartPosY() {
		return startPosY;
	}
}
